package com.lottery.game.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;

/**
 * 图片工具类
 */
@Slf4j
public class ImgUtils {

    //上传图片存储路径 --聊天
    public static final String CHATIMG_PATH = "chatPicture/";
    //上传图片存储路径  -- 头像
    public static final String HEADIMG_PATH = "profilePicture/";
    //过滤器拦截图片的匹配
    public static final String FILTER_IMAGE = "/lotteryImg";

    public static final DateTimeFormatter YEAR_MONTH_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM");
    /**
     * 获取文件后缀
     *
     * @param fileName
     * @return
     */
    public static String getSuffix(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 生成新的文件名
     *
     * @param fileOriginName 源文件名
     * @return
     */
    public static String getFileName(String fileOriginName,String pathType) {
        return pathType+ UUID.randomUUID() + ImgUtils.getSuffix(fileOriginName);
    }

    /**
     * 如果不存在则创建图片的目录
     *
     * @return
     */
    public static void getImgDir(String dir) {

        File file = new File(dir);
        Boolean bbc = file.mkdirs();
        log.info("创建指定目录" + dir);
    }

    /**
     * @param file
     * @param pathType   图片存储文件夹类型
     * @throws Exception
     */
    public static String uploadImg(MultipartFile file[], String pathType) {

        StringBuffer imgName = new StringBuffer();
        String imgTemp = "";
        try {
            if (null == file) {
                return imgName.toString();
            }
            // 设置上传的路径
            String imgPath = getImgPath() + pathType;
            for (int i = 0; i < file.length; i++) {
                imgTemp = getFileName( file[i].getOriginalFilename(),"");
                //上传文件
                uploadFileUtil(file[i].getBytes(), imgPath, imgTemp);
                imgName.append(pathType).append(imgTemp);
                if (i != file.length - 1) {
                    imgName.append(",");
                }
            }
            log.info("uploadImg图片上传路径加名字@" + imgPath + imgName);
        } catch (Exception e) {
            log.error("上传失败");
        }
        return imgName.toString();

    }

    /**
     * @param file
     * @param pathType   名字前缀
     * @throws Exception
     */
    public static String uploadImg(MultipartFile file, String pathType){


        String imgName = "";
        try {
            if (null == file) {
                return imgName;
            }
            log.info("uploadImg");
            // 设置上传的路径
            String imgPath = getImgPath() + pathType;
            imgName = getFileName(file.getOriginalFilename(),"");
            //上传文件
            uploadFileUtil(file.getBytes(), imgPath, imgName);
            imgName = pathType+imgName;
        } catch (Exception e) {
            log.error("上传失败");
        }
        return imgName;

    }

    /**
     * 取得图片的绝对路径
     *
     * @return
     */
    public static String getImgPath() {
        return SpringApplicationContext.getApplicationContext().getEnvironment().getProperty("lotteryapi.resource.upload");
    }

    /**
     * 上传文件的方法
     *
     * @param file：文件的字节
     * @param imgPath：文件的路径
     * @param imgName：文件的名字
     * @throws Exception
     */
    public static void uploadFileUtil(byte[] file, String imgPath, String imgName) throws Exception {

        File targetFile = new File(imgPath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(imgPath + imgName);
        out.write(file);
        out.flush();
        out.close();
    }

    /***
     * 删除指定文件夹下所有文件
     * @param path 文件夹完整绝对路径
     * @return
     */
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);// 再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    /***
     * 删除文件夹
     * @param folderPath 文件夹完整绝对路径
     */
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); // 删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);
            myFilePath.delete(); // 删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
